//
//  ImageCategoryView.swift
//  PhotoTestDemo
//
//  Created by 惠 on 2020/9/9.
//  Copyright © 2020 惠. All rights reserved.
//

import UIKit
import Photos

//相簿列表项
class AlbumItem {
    //相簿名称
    var title:String?
    //相簿内的资源
    var fetchResult:PHFetchResult<PHAsset>
    
    init(title:String?,fetchResult:PHFetchResult<PHAsset>) {
        self.title = title
        self.fetchResult = fetchResult
    }
}

class ImageCategoryView: UIView {
    let screenW = UIScreen.main.bounds.width
    let screenH = UIScreen.main.bounds.height
    
    //相簿列表项集合
    var items:[AlbumItem] = []
    //用来存放Cell的唯一标示符
    var cellDic: [String: String] = [:]
    var selectedCell: Int?
    
    private var colorType: ColorType!
    init(colorType: ColorType = .defaults, frame: CGRect) {
        super.init(frame: frame)
        
        self.colorType = colorType
        setUI()
        albumsContent()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUI()
        albumsContent()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    //MARK: -懒加载UI
    lazy var categoryTableView: UITableView = {
        let categoryTableView = UITableView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: screenW, height: screenH-200)), style: .plain)
        categoryTableView.dataSource = self
        categoryTableView.delegate = self
        categoryTableView.rowHeight = 69
        categoryTableView.separatorColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1)
        return categoryTableView
    }()
    
    lazy var alphaButton: UIButton = {
        let alphaButton = UIButton(type: .custom)
        alphaButton.frame = CGRect(origin: CGPoint(x: 0, y: screenH-200), size: CGSize(width: screenW, height: 200))
        alphaButton.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7)
        return alphaButton
    }()
    
    //MARK: -设置UI
    func setUI() {
        backgroundColor = .clear
        
        addSubview(categoryTableView)
        addSubview(alphaButton)
    }
    
//MARK: -相册列表
    func albumsContent() {
        items.removeAll()
        // 列出所有系统的智能相册
        let smartOptions = PHFetchOptions()
        let smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum,
                                                                  subtype: PHAssetCollectionSubtype.albumRegular,
                                                                  options: smartOptions)
        self.convertCollection(collection: smartAlbums)
        
        
        //列出所有用户创建的相册
        let userCollections = PHCollectionList.fetchTopLevelUserCollections(with: nil) as? PHFetchResult<PHAssetCollection>
        if let userC = userCollections {
            self.convertCollection(collection: userC)
        }

    }
    
    //转化处理获取到的相簿
    private func convertCollection(collection:PHFetchResult<PHAssetCollection>){
        for i in 0..<collection.count{
            //获取相簿内的图片和视频
            let resultsOptions = PHFetchOptions()
            resultsOptions.sortDescriptors = [NSSortDescriptor(key: "modificationDate",
                                                               ascending: false)]
            //添加只获取相簿内的图片
//            resultsOptions.predicate = NSPredicate(format: "mediaType = %d",
//                                                   PHAssetMediaType.image.rawValue)
            let c = collection[i]
            let assetsFetchResult = PHAsset.fetchAssets(in: c ,
                                                        options: resultsOptions)
            //没有图片的空相簿不显示
            if assetsFetchResult.count > 0{
                if let title = albumChinseTitle(title: c.localizedTitle) {
                    items.append(AlbumItem(title: title, fetchResult: assetsFetchResult))
                }
            }
        }
        categoryTableView.reloadData()
        
    }
    
    func albumChinseTitle(title: String?) -> String? {
        guard let title = title else {
            return nil
        }
        switch title {
        case "Slo-mo":
            return "慢动作"
        case "Recently Added":
            return "最近添加"
        case "Favorites":
            return "个人收藏"
        case "Recently Deleted":
            return "最近删除"
        case "Videos":
            return "视频"
        case "Recents":
            return "所有照片"
        case "Selfies":
            return "自拍"
        case "Screenshots":
            return "屏幕快照"
        case "Camera Roll":
            return "相机胶卷"
        case "Panoramas":
            return "全景照片"
        case "Time-lapse":
            return "延时摄影"
        case "Animated":
            return "动图"
        case "Long Exposure":
            return "长曝光"
        case "Portrait":
            return "人像"
        case "Hidden":
            return nil
        case "Bursts":
            return "连拍快照"
        case "Live Photos":
            return "实况照片"
        default:
            return title
        }
    }
    
}

extension ImageCategoryView: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var identifier = cellDic["\(indexPath)"]
        if identifier == nil {
            identifier = "ImageCategoryTableViewCell\(indexPath)"
            cellDic["\(indexPath)"] = identifier
            categoryTableView.register(ImageCategoryTableViewCell.classForCoder(), forCellReuseIdentifier: identifier!)
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: identifier!, for: indexPath) as! ImageCategoryTableViewCell
        cell.colorType = colorType
        cell.selectionStyle = .none
        let item = self.items[indexPath.row]
        cell.titleLabel.text = item.title
        cell.countLabel.text = "\(item.fetchResult.count)"
        if selectedCell != nil && selectedCell == indexPath.row {
            cell.selectItemImage.isHidden = false
        } else {
            cell.selectItemImage.isHidden = true
        }
        //获取缩略图
        let imageManager = PHCachingImageManager()
        imageManager.requestImage(for: item.fetchResult[0], targetSize: CGSize(width: 50, height: 50),
                                  contentMode: PHImageContentMode.aspectFill,
                                  options: nil) { (image, nfo) in
                                    cell.contentImage.image = image
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as? ImageCategoryTableViewCell
        cell?.selectItemImage.isHidden = false
        selectedCell = indexPath.row
        let item = self.items[indexPath.row]
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "imageCategory"), object: self, userInfo: ["asset": item])
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "bottonSelect"), object: self, userInfo: ["asset": item])
    }
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as? ImageCategoryTableViewCell
        cell?.selectItemImage.isHidden = true
    }
}
